const nodeSchedule = require('node-schedule')
const { models } = require('../../model')
const { sendSubscribe } = require('../tophub')
const { sendDingTalk, sendFeishu, sendWechat } = require('./msg')
// utils
const { formatScheduleRule } = require('../../utils/schedule')
const { cloneDeep } = require('lodash')

// const Model = require('prototype/Model')
// env
const isProduction = process.env.NODE_ENV === 'production'
const isDevelopment = process.env.NODE_ENV === 'development'

let runningSchedules = {}

async function initSchedules () {
  const channels = await models.MsgChannel.collection.find({}).toArray()
  const robots = await models.MsgRobot.collection.find({}).toArray()
  const subscribes = await models.UserTophub.find({ status: 1 }).toArray()
  const schedules = []
  robots.forEach(e => {
    e.scheduleFrom = 'robotMsg'
    schedules.push(e)
  })
  subscribes.forEach(e => {
    e.rules.forEach(r => {
      const s = cloneDeep(e)
      s.scheduleFrom = 'subscribe'
      s.rule = r
      schedules.push(s)
    })
  })
  // 清空所有计划任务
  Object.keys(runningSchedules).forEach(key => {
    const runningSchedule = runningSchedules[key]
    if (runningSchedule.job) {
      runningSchedule.job.cancel()
    }
  })
  runningSchedules = {}
  // 重新构建所有计划任务
  schedules.forEach(schedule => {
    const id = schedule._id.toString()
    const runningSchedule = runningSchedules[id] = schedule
    // 格式化定时任务规则
    if (runningSchedule.scheduleFrom !== 'subscribe') {
      runningSchedule.rule = formatScheduleRule(runningSchedule.rule)
    }
    isDevelopment && console.log('Init Rule:', runningSchedule.message, runningSchedule.rule)
    runningSchedule.job = nodeSchedule.scheduleJob(runningSchedule.rule, async function () {
      isDevelopment && console.log('Send Message:', JSON.stringify(runningSchedule))
      if (runningSchedule.scheduleFrom === 'subscribe') {
        await sendSubscribe(runningSchedule)
      }
      if (isProduction) {
        if (runningSchedule.scheduleFrom === 'subscribe') {
          await sendSubscribe(runningSchedule)
        } else if (runningSchedule.scheduleFrom === 'msgRobot') {
          if (runningSchedule.webhookUrl) {
            sendWechat(runningSchedule)
          }
          // 钉钉机器人消息发送
          if (runningSchedule.accessToken) {
            sendDingTalk(runningSchedule)
          }
          // 飞书机器人消息发送
          if (runningSchedule.feishuWebhookUrl) {
            sendFeishu(runningSchedule)
          }
          // 多通道消息发送
          if (runningSchedules.channels) {
            runningSchedules.channels.forEach(id => {
              const channel = channels.find(e => e._id.toString() === id)
              if (channel.platform === 1) {
                sendWechat({
                  webhookUrl: channel.webhook,
                  message: runningSchedules.message
                })
              }
              if (channel.platform === 2) {
                sendDingTalk({
                  accessToken: channel.webhook,
                  secret: channel.accessToken,
                  message: runningSchedules.message
                })
              }
              if (channel.platform === 3) {
                sendFeishu({
                  feishuWebhookUrl: channel.webhook,
                  message: runningSchedules.message
                })
              }
            })
          }
        }
      }
    })
  })
  // console.log('Init schedule success')
  return `Init schedule success: ${schedules.length}`
}

module.exports = {
  initSchedules
}
